//
//  SmsCloudApplePay.m
#import "SmsCloudApplePay.h"
#import <StoreKit/StoreKit.h>
@interface SmsCloudApplePay()<SKProductsRequestDelegate,SKPaymentTransactionObserver>
@property (nonatomic, copy)NSString * productId;
@property (nonatomic, strong) SKPaymentTransaction* paymentTran;
@end
@implementation SmsCloudApplePay
static SmsCloudApplePay *defaultManager = nil;
 + (SmsCloudApplePay*)defaultRequest{
     static dispatch_once_t token;
     dispatch_once(&token, ^{
         if(defaultManager == nil){
             defaultManager = [[SmsCloudApplePay alloc] init];
             [[SKPaymentQueue defaultQueue] addTransactionObserver:defaultManager];
         }
     });
     return defaultManager;
}
- (void)applePayProId:(NSString *)proId{
    if (proId.length > 0) {
        self.productId = proId;
        if (self.paymentTran) {
            [[SKPaymentQueue defaultQueue] finishTransaction: self.paymentTran];
        }
        [SVProgressHUD showWithStatus:@"支付中"];
        //请求产品
        NSArray *product = [[NSArray alloc] initWithObjects:proId,nil];
        NSSet *set = [NSSet setWithArray:product];
        SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
        productsRequest.delegate = self;
        [productsRequest start];
    }
}
- (void)completeTransaction:(SKPaymentTransaction*)transaction{
    self.paymentTran = transaction;
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    [self localReceiptVerifyingWithUrl:[SmsCloudHead SmsCloudUrlSandboxUrl] AndReceipt:receiptString AndTransaction:transaction];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)finshTransaction:(SKPaymentTransaction*)transaction{
    self.paymentTran = transaction;
    [SVProgressHUD dismiss];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
/// 请求苹果接口进行票据校验
- (void)localReceiptVerifyingWithUrl:(NSString *)requestUrl AndReceipt:(NSString *)receiptStr AndTransaction:(SKPaymentTransaction *)transaction{
    __weak __typeof__(self) weakSelf = self;
    NSDictionary *requestDic = @{@"receipt-data": receiptStr,@"password":[SmsCloudHead SmsCloudPublicAppProductKey],@"exclude-old-transactions":@(true)};
    // 转换为 JSON 格式
    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestDic options:0 error:nil];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[[NSURL alloc] initWithString:requestUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:requestData];
    
    // 在后台对列中提交验证请求，并获得官方的验证JSON结果
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error) {
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        } else {
            NSError *error;
            NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (!jsonResponse) {
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(weakSelf.ApplePayScuBlock){
                        weakSelf.ApplePayScuBlock();
                    }
                });
            }
        }
    }];
    [task resume];
}

#pragma mark - SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response{
    NSArray *product = response.products;
    if(product && product.count > 0){
        for (int i = 0; i < product.count; i++) {
            SKProduct *pro = product[i];
            if ([pro.productIdentifier isEqualToString:self.productId]) {
                SKPayment *payment = [SKPayment paymentWithProduct:pro];
                [[SKPaymentQueue defaultQueue] addPayment:payment];
            }
        }
    }else{
        [SVProgressHUD dismiss];
    }
}
//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
}
#pragma mark - SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray *)transactions{
    for(SKPaymentTransaction *tran in transactions){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{//交易完成
                [self completeTransaction:tran];
            }
            break;
            case SKPaymentTransactionStateRestored:{//已经购买过该商品
                if(self.ApplePayScuBlock){
                    self.ApplePayScuBlock();
                }
                [SVProgressHUD dismiss];
                [queue finishTransaction:tran];
            }
            break;
            case SKPaymentTransactionStateFailed:{//购买失败
                [self finshTransaction:tran];
            }
            break;
            default:
                break;
        }
    }
}
-(void)dealloc{
    [[SKPaymentQueue defaultQueue] finishTransaction:self.paymentTran];
}
@end
